package com.hdax.gulimall.product.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.hdax.gulimall.product.entity.PmsCategoryEntity;
import com.hdax.gulimall.product.service.PmsCategoryService;
import com.hdax.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 使用redis
 * 1、导入对应的依赖
 * 2、写配置
 * 3.使用StringRedisTemplate类来进行缓存
 */

@Controller
public class IndexController {


    @Autowired
    private PmsCategoryService pmsCategoryService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 首页数据
     * @param model
     * @return
     */
    @GetMapping({"/","index.html"})
    public String index(Model model){
        List<PmsCategoryEntity> list=pmsCategoryService.getLevel1Category();
        model.addAttribute("categorys",list);
        //查出所有的一级分类
        //他有一个默认的前缀 classpath:/templates/
        //.html默认的后缀
        return "index";
    }


    /**
     * 子分类
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @GetMapping("/index/catalog/index.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson() throws JsonProcessingException {
        Map<String, List<Catalog2Vo>> map=pmsCategoryService.getCatalogJson();
        return map;
    }


    @ResponseBody
    @RequestMapping("/gag")
    public String haha(){

        //获取一把锁
        RLock lock = redissonClient.getLock("my-lock");

        //十秒后会自动解锁
        lock.lock(10, TimeUnit.SECONDS);
        //加锁
        lock.lock();

        //解锁
        lock.unlock();
        System.out.println(redissonClient);
        return "gaga";
    }
}
